/*
 * Copyright (c) 2009 Sun Microsystems, Inc.
 * Copyright (c) 2011 Oracle Corporation.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to
 * deal in the Software without restriction, including without limitation the
 * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
 * sell copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
 **/

package org.sunspotworld.demo;

import com.sun.spot.wot.gateway.Device;
import com.sun.spot.wot.gateway.DeviceManager;
import java.io.IOException;
import com.sun.spot.wot.WebApplication;
import com.sun.spot.wot.http.HttpRequest;
import com.sun.spot.wot.http.HttpResponse;

/**
 *
 * @author vgupta
 */
public class ResourceCacheApp extends WebApplication {

    public ResourceCacheApp() {
    }

    ResourceCacheApp(String string) {
        super(string);
    }

    @Override
    public void init() {
        System.out.println("Started ResourceCache manager ...");
    }

    @Override
    public HttpResponse processRequest(HttpRequest req) throws IOException {
        int idx = -1;
        String pathInfo = req.getPathInfo();
        HttpResponse res = new HttpResponse();

        if ((pathInfo == null) || ((idx = pathInfo.indexOf("/", 1)) < 1)) {
            res.setStatus(HttpResponse.SC_BAD_REQUEST);
        } else {
            String deviceId = pathInfo.substring(1, idx);
            Device dev = DeviceManager.findByName(deviceId);
            if (dev == null) {
                //System.out.println("Did not find device " + deviceId);
                res.setStatus(HttpResponse.SC_NOT_FOUND);
            } else {
                // Show all resources ...
                res.setStatus(HttpResponse.SC_OK);
                res.setHeader("Content-Type", "text/plain");
                byte[] body = ("Resource Cache for device " + deviceId +
                        "\n===========================\n" +
                        dev.getResourceCache().toString()).getBytes();
                res.setBody(body);
            }
        }

        return res;
    }
}
